using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 工单修改命令。
/// </summary>
public sealed record UpdateWorkOrderCommand(long Id, ProdWorkOrderDto WorkOrder) : IRequest<IResult<bool>>;

internal sealed class UpdateWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<UpdateWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateWorkOrderCommand request, CancellationToken cancellationToken)
    {
        // 检查单号不能重复
        if (await repo.IsAnyAsync(m => m.Wo == request.WorkOrder.Wo && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("工单单号已存在");
        }

        var workOrder = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找到要更新的工单");
        }

        // 检测工单状态，只有在草稿状态才能修改
        if (workOrder.Status is not WoStatusEnum.Draft)
        {
            return Result.Failure("工单只有在草稿状态才能修改");
        }

        workOrder.ProductId = request.WorkOrder.ProductId;
        workOrder.LineId = request.WorkOrder.LineId;
        workOrder.WoType = request.WorkOrder.WoType;
        workOrder.PlanQty = request.WorkOrder.PlanQty;
        workOrder.PlanStartDate = request.WorkOrder.PlanStartDate;
        workOrder.PlanEndDate = request.WorkOrder.PlanEndDate;
        workOrder.IsMaster = request.WorkOrder.IsMaster;
        workOrder.Source = request.WorkOrder.Source;
        workOrder.BatchNo = request.WorkOrder.BatchNo;
        workOrder.Remark = request.WorkOrder.Remark;

        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.ProductId,
            m.LineId,
            m.WoType,
            m.PlanQty,
            m.PlanStartDate,
            m.PlanEndDate,
            m.IsMaster,
            m.Source,
            m.BatchNo,
            m.Remark,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
